<template>
  <view class="post-page">

    <header class="header">
      <image class="header-image" src="/static/header-bg.png" mode="aspectFill"></image>
      <view class="header-bar">
        <image class="back-btn" src="/static/back-icon.png" mode="aspectFit" @click="goBack"></image>
        <image v-if="!isEditMode" class="page-title-image" src="/static/publish-dynamic.png" mode="aspectFit"></image>
        <text v-else class="page-title">编辑动态</text>
      </view>
    </header>

    <!-- 内容卡片区域 -->
    <view class="post-card">
      <!-- 文本输入大框 -->
      <textarea 
        v-model="postText"
        class="post-textarea"
        placeholder="请输入500字以内的内容"
        maxlength="500"
        auto-height
      ></textarea>

      <!-- 上传占位卡 -->
      <view class="upload-card" @click="addMedia">
        <image class="camera-icon" src="/static/up-photo.png" mode="aspectFit"></image>
        <text class="upload-text">点击上传</text>
      </view>

      <!-- 提示文案 -->
      <text class="tips">请上传4:3比例，大小2m以内jpg、png图片</text>

      <!-- 已选媒体预览 -->
      <view v-if="isSingleVideo" class="single-video">
        <video 
          :src="mediaFiles[0].url" 
          class="single-video-el" 
          controls 
          :show-center-play-btn="true"
        ></video>
        <!-- H5 等平台 -->
        <view class="gallery-delete no-bg" @click.stop="removeMedia(0)">
          <image class="delete-icon" src="/static/del.png" mode="aspectFit" />
        </view>
        <!-- 小程序平台覆盖层 -->
        <cover-view class="gallery-delete no-bg" @click.stop="removeMedia(0)">
          <cover-image class="delete-icon" src="/static/del.png" />
        </cover-view>
      </view>
      <view v-else class="gallery">
        <view 
          v-for="(media, index) in mediaFiles" 
          :key="index"
          class="gallery-item"
        >
          <image v-if="media.type === 'image'" :src="media.url" class="gallery-image" mode="aspectFill"></image>
          <video 
            v-else-if="media.type === 'video'" 
            :src="media.url" 
            class="gallery-video" 
            controls 
            :show-center-play-btn="true"
          ></video>
          <!-- H5 等平台 -->
          <view :class="['gallery-delete', media.type === 'video' ? 'no-bg' : '']" @click.stop="removeMedia(index)">
            <image class="delete-icon" src="/static/del.png" mode="aspectFit" />
          </view>
          <!-- 小程序平台覆盖层 -->
          <cover-view :class="['gallery-delete', media.type === 'video' ? 'no-bg' : '']" @click.stop="removeMedia(index)">
            <cover-image class="delete-icon" src="/static/del.png" />
          </cover-view>
        </view>
      </view>
    </view>

    <!-- 发布/更新按钮 -->
    <view class="publish-section">
      <button class="publish-primary" :disabled="!canPublish" @click="handlePublish">{{ isEditMode ? '更新' : '发布' }}</button>
    </view>
  </view>
</template>

<script>
// import CommunityApi from '@/sheep/api/index/community'
import user from '@/sheep/store/user'
import FileApi from '@/sheep/api/infra/file'

export default {
  name: 'PostPage',
  data() {
    return {
      editId: null,
      postText: '',
      visibilityIndex: 0,
      visibilityOptions: ['公开', '仅粉丝可见', '仅自己可见'],
      mediaFiles: [],
      tags: [],
      tagInput: '',
      location: '',
      userStore: user(),
      isLoading: false
    }
  },
  computed: {
    isEditMode() {
      return !!this.editId
    },
    canPublish() {
      return this.postText.trim().length > 0 || this.mediaFiles.length > 0
    },
    isSingleVideo() {
      return this.mediaFiles.length === 1 && this.mediaFiles[0]?.type === 'video'
    }
  },
  methods: {
    goBack() {
      uni.navigateBack()
    },
    
    onVisibilityChange(e) {
      this.visibilityIndex = e.detail.value
    },
    
    async handlePublish() {
      if (!this.canPublish) {
        uni.showToast({
          title: '请输入内容',
          icon: 'none'
        })
        return
      }
      
      // 检查登录状态
      const token = uni.getStorageSync('token')
      const isLogin = this.userStore?.isLogin || !!token
      
      if (!isLogin) {
        uni.showToast({ title: '请先登录', icon: 'none' })
        // 跳转到登录页
        setTimeout(() => {
          uni.navigateTo({
            url: '/pages/index/login'
          })
        }, 1500)
        return
      }
      
      // 如果已登录但用户信息未加载，尝试获取用户信息
      let userId = this.userStore?.userInfo?.id || this.userStore?.userInfo?.userId
      if (!userId && isLogin) {
        try {
          // 尝试获取用户信息
          if (this.userStore && this.userStore.getInfo) {
            await this.userStore.getInfo()
            userId = this.userStore?.userInfo?.id || this.userStore?.userInfo?.userId
          }
        } catch (error) {
          console.error('获取用户信息失败:', error)
        }
      }
      
      if (!userId) {
        uni.showToast({ title: '获取用户信息失败，请重新登录', icon: 'none' })
        setTimeout(() => {
          uni.navigateTo({
            url: '/pages/index/login'
          })
        }, 1500)
        return
      }

      const images = this.mediaFiles
        .filter(m => m.type === 'image' && m.url)
        .map(m => m.url)
      const video = this.mediaFiles.find(m => m.type === 'video')?.url || ''

      uni.showLoading({ title: this.isEditMode ? '更新中...' : '发布中...' })
      try {
        const CommunityApi = (await import('@/sheep/api/index/community')).default
        let res
        if (this.isEditMode) {
          // 编辑模式
          const params = {
            id: this.editId,
            content: this.postText?.trim() || '',
            images,
            video
          }
          res = await CommunityApi.updateCommunity(params)
        } else {
          // 发布模式
          const params = {
            userId,
            content: this.postText?.trim() || '',
            images,
            video
          }
          res = await CommunityApi.publishCommunity(params)
        }
        // 成功提示由请求层处理，此处做导航返回
        if (res && res.code === 0) {
          setTimeout(() => {
            uni.navigateBack()
          }, 500)
        }
      } catch (e) {
        // 请求层会处理错误提示，这里不重复提示
      } finally {
        uni.hideLoading()
      }
    },
    
    // 加载动态详情用于编辑
    async loadDynamicDetail() {
      if (!this.editId) return
      
      this.isLoading = true
      try {
        const CommunityApi = (await import('@/sheep/api/index/community')).default
        const res = await CommunityApi.getCommunityDetail({ id: this.editId })
        if (res && res.code === 0 && res.data) {
          const data = res.data
          
          // 回显文本内容
          this.postText = data.content || ''
          
          // 回显图片
          this.mediaFiles = []
          if (data.images && data.images.length > 0) {
            // 处理图片数据（可能是字符串或数组）
            let imageList = []
            if (typeof data.images === 'string') {
              imageList = data.images.split(',').filter(img => img.trim())
            } else if (Array.isArray(data.images)) {
              imageList = data.images
            }
            
            // 添加到媒体文件列表
            imageList.forEach(url => {
              if (url) {
                this.mediaFiles.push({ url: url.trim(), type: 'image' })
              }
            })
          }
          
          // 回显视频
          if (data.video) {
            let videoUrl = ''
            if (typeof data.video === 'string' && data.video.trim()) {
              videoUrl = data.video.trim()
            } else if (Array.isArray(data.video) && data.video.length > 0) {
              videoUrl = data.video[0]
            }
            
            if (videoUrl) {
              this.mediaFiles.push({ url: videoUrl, type: 'video' })
            }
          }
        } else {
          uni.showToast({
            title: res?.msg || '加载动态失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('加载动态详情失败:', error)
        uni.showToast({
          title: '加载失败，请重试',
          icon: 'none'
        })
      } finally {
        this.isLoading = false
      }
    },
    
    async addMedia() {
      const remain = 9 - this.mediaFiles.length
      if (remain <= 0) {
        uni.showToast({ title: '最多选择9个媒体', icon: 'none' })
        return
      }

      uni.showActionSheet({
        itemList: ['图片', '视频'],
        success: async (res) => {
          const index = res.tapIndex
          const hasVideo = this.mediaFiles.some(m => m.type === 'video')
          const hasImages = this.mediaFiles.some(m => m.type === 'image')
          if (index === 0) {
            if (hasVideo) {
              uni.showToast({ title: '图片和视频不能同时选择，请先删除视频', icon: 'none' })
              return
            }
            // 图片
            uni.chooseImage({
              count: remain,
              success: async (pick) => {
                try {
                  const tasks = (pick.tempFilePaths || []).map(async (path) => {
                    const result = await FileApi.uploadFile(path, 'community')
                    const url = result?.data
                    return url ? { url, type: 'image' } : null
                  })
                  const uploaded = (await Promise.all(tasks)).filter(Boolean)
                  this.mediaFiles = [...this.mediaFiles, ...uploaded]
                } catch (e) {}
              }
            })
          } else if (index === 1) {
            // 视频（仅允许一个）
            if (hasVideo) {
              uni.showToast({ title: '已选择视频', icon: 'none' })
              return
            }
            if (hasImages) {
              uni.showToast({ title: '图片和视频不能同时选择，请先删除图片', icon: 'none' })
              return
            }
            uni.chooseVideo({
              sourceType: ['album', 'camera'],
              camera: 'back',
              maxDuration: 60,
              compressed: true,
              success: async (pick) => {
                try {
                  const path = pick.tempFilePath
                  const result = await FileApi.uploadFile(path, 'community')
                  const url = result?.data
                  if (url) {
                    this.mediaFiles = [...this.mediaFiles, { url, type: 'video' }]
                  }
                } catch (e) {}
              }
            })
          }
        }
      })
    },
    
    removeMedia(index) {
      this.mediaFiles.splice(index, 1)
    },
    
    addTag() {
      const tag = this.tagInput.trim()
      if (tag && !this.tags.includes(tag)) {
        this.tags.push(tag)
        this.tagInput = ''
      }
    },
    
    removeTag(index) {
      this.tags.splice(index, 1)
    },
    
    selectLocation() {
      uni.chooseLocation({
        success: (res) => {
          this.location = res.name
        },
        fail: () => {
          uni.showToast({
            title: '定位失败',
            icon: 'none'
          })
        }
      })
    }
  },
  onLoad(options) {
    // 检查是否是编辑模式
    if (options.editId) {
      this.editId = options.editId
      // 加载动态详情
      this.loadDynamicDetail()
    }
  }
}
</script>

<style lang="scss" scoped>
.post-page {
  min-height: 100vh;
  background: #f6f6f6;
}

.back-btn {
  width: 80rpx;
  height: 80rpx;
  /* 如果需要调整位置，可以添加以下样式 */
  /* position: absolute;
  left: 20rpx;
  top: 20rpx; */
}

.page-title-image { 
  width: 160rpx;  /* 根据需要调整宽度 */
  height: 50rpx;  /* 根据需要调整高度 */
}

.page-title {
  font-size: 56rpx;
  font-weight: 800;
  color: #000;
}

.header {
  position: relative;
  height: 360rpx;
  z-index: 0;
}
.header-image {
  position: absolute;
  top: 0; left: 0; right: 0; bottom: 0;
  width: 100%; height: 100%;
}

.header-bar {
  position: absolute;
  top: 60rpx; 
  left: 24rpx; 
  right: 24rpx;
  display: flex; 
  align-items: center; 
  gap: 16rpx;
}
.back-btn { 
  font-size: 40rpx; 
  color: #000; 
}
.page-title { 
  font-size: 56rpx; 
  font-weight: 800; 
  color: #000; 
}

.post-card {
  background: #fff;
  margin: -190rpx 24rpx 24rpx;
  border-radius: 24rpx;
  padding: 24rpx;
  position: relative; 
  z-index: 10;
}

.post-textarea {
  width: 100%; 
  min-height: 280rpx;
  background: #f7f7f9; 
  border-radius: 16rpx;
  padding: 20rpx; 
  box-sizing: border-box;
  font-size: 28rpx; 
  color: #333;
  margin-top: 20rpx;
}

.upload-card {
  margin-top: 24rpx; 
  height: 260rpx; 
  width: 50%;
  background: #f7f7f9;
  border-radius: 16rpx; 
  display: flex; 
  flex-direction: column;
  align-items: center; 
  justify-content: center;
}
.camera-icon { 
  width: 80rpx; 
  height: 80rpx; 
  opacity: .9; 
}
.upload-text { 
  margin-top: 12rpx; 
  font-size: 24rpx; 
  color: #666; }

.tips { display: block; margin: 24rpx 4rpx; font-size: 26rpx; color: #8a8f98; }

.gallery { 
  display: flex; 
  flex-wrap: wrap;
  gap: 12rpx; 
  margin-top: 24rpx;
}
.gallery-item { 
  width: calc((100% - 24rpx) / 3); 
  height: 200rpx; 
  position: relative; 
  border-radius: 16rpx; 
  overflow: hidden; 
}
.gallery-image { 
  width: 100%; 
  height: 100%; 
}
.gallery-video {
  width: 100%;
  height: 100%;
}

/* 单视频预览，参照列表页视频尺寸 */
.single-video {
  margin-top: 24rpx;
  position: relative;
}
.single-video-el {
  width: 100%;
  height: 400rpx;
  border-radius: 10rpx;
}
.gallery-delete { 
  position: absolute; 
  top: 0; 
  right: 0; 
  background: rgba(0,0,0,.75); 
  padding: 5rpx 8rpx; 
  border-bottom-left-radius: 12rpx; 
  z-index: 999;
}

.delete-icon {
  width: 28rpx;
  height: 28rpx;
}

.gallery-delete.no-bg {
  background: transparent !important;
}

.publish-section {
  margin-top: 40rpx;
  padding: 0 24rpx;
}

.publish-primary {
  width: 100%; 
  height: 96rpx; 
  line-height: 96rpx; 
  border-radius: 48rpx;
  color: #fff; 
  font-size: 32rpx; 
  border: none;
  background: linear-gradient(90deg,#B276FF 0%, #74A7FF 100%);
}

.publish-primary[disabled] { 
  opacity: .5; 
}
</style>
